
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  query.query;


import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import logger.PoolLogger;
import query.groupby.Groupbyinterface;
import sort.Ascending;
import utility.Addprefix;
import utility.CapitalChar;
import utility.ConvertToLower;
import database.RecordSearch;
import dbmanager.Column;
import dbmanager.DBManager;
import dbmanager.GetIdName;

public class Groupby implements Queryinterface 
{
	DBManager  database;
	String object;
	String buffer[];
	String ReportName;
	String Querybuffer[];
	String QueryName;
	String Key;
	String tablename;
	String Value;
	Hashtable<Object, Object> Querymap = new Hashtable<Object, Object>();
	Hashtable<Object, Object> ReportMap =new Hashtable<Object, Object>();
	String tid;
	GetIdName gid;
	String Field;
	String field;
	String typeofreport;
	String reporton;
	PoolLogger pl;
	
	public Groupby() {
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	
	
	public String[] executeQuery(){return null;}
	
	public void addReport() 
	{	
		Hashtable<Object,Object> table =new Hashtable<Object, Object>();
		table.put("mid", object);
		RecordSearch rs = new RecordSearch();
		rs.setConditionMap(table);
		String line[] = rs.getArrayFromResultSet();
		table.clear();
		for(int i=0;i<line.length;i++)
		{
			String splitline[] = line[i].split("\t");
			String value = splitline[Column.pv_index-1];
			if(value.equals("0"))
				value = splitline[Column.vt_index-1];
			else
				value = gid.getItem(value);
			table.put(gid.getItem(splitline[Column.pid_index-1]), value);
		}
		table = ConvertToLower.convertHashKey(table);
		
		if(table.containsKey("field"))
		{
			 field = table.get("field").toString();
		}
		
		
		Ascending ascending = new Ascending();
		ascending.setbuffer(buffer);
		Vector<Object>temp = new Vector<Object>();
		//String[] tempbuffer1= buffer[0].split("\t"); 
		String[] tempbuffer1= Addprefix.removerefix(buffer[0]).split("\t"); 
		for(int i=0;i<tempbuffer1.length;i++)
		{
			if(tempbuffer1[i].toLowerCase().equals(field.toLowerCase()))
				temp.add(i);
		}
		ascending.setVector(temp,1);
		ascending.getResult();
		buffer = ascending.getbuffer();
		temp.clear();
		int indeoffield=-1;
		String splitbuffer[] = Addprefix.removerefix(buffer[0]).split("\t");
		for(int i=0;i<splitbuffer.length;i++)
		{
			if(splitbuffer[i].toLowerCase().equals(field.toLowerCase()))
				indeoffield = i;
		}
		
		for(int i=1;i<buffer.length;i++)
		{
			try 
			{
				splitbuffer = buffer[i].split("\t");
				String value =splitbuffer[indeoffield];
				String pre_value=value;
				StringBuffer newbuffer = new StringBuffer();
				int j=i;
				while(value.equals(pre_value))
				{	
					pre_value = value;
					newbuffer.append(buffer[j]+"\n");
					try 
					{
						j++;
						splitbuffer = buffer[j].split("\t");
						value =splitbuffer[indeoffield];
					}
					catch (Exception e) 
					{
						value="";
						i++;
						e.printStackTrace();
					}
				}
				i=j-1;
				temp.add(newbuffer.toString().split("\n"));
				//i++;
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		Vector<Object> Result = new Vector<Object>();
		
		String heading = null;
		Enumeration<Object> enumerationtable = table.keys();
		while(enumerationtable.hasMoreElements())
		{
			String key = enumerationtable.nextElement().toString();
			String value = table.get(key).toString();
			Groupbyinterface group;
			try 
			{
				for(int i=0;i<temp.size();i++)
				{
					Class c = Class.forName("combinereport.query.groupby."+CapitalChar.makeFirstCharCapital(key));
					group = (Groupbyinterface) c.newInstance();
					group.setBuffer((String[]) temp.get(i));
					group.initPool();
					group.setobject(gid.getId(table.get(key).toString()));
					group.setField(field);
					group.setheading(buffer[0]);
					group.settypeofreport(typeofreport);
					group.setReportMap(ReportMap);
					group.setReportName(ReportName);
					group.setreporton(reporton);
					group.addReport();					
					Field = group.getField();
					Result.add(group.getBuffer());
					heading =group.getheading();
				}
				temp.clear();
				for(int k=0;k<Result.size();k++)
				{
					String tempbuffer[] = (String[]) Result.get(k);
					for(int iVar=0;iVar<tempbuffer.length;iVar++)
					{
						temp.add(tempbuffer[iVar]);
					}
				}
				StringBuffer tempbuffer = new StringBuffer();
				if(heading.contains(field))
					tempbuffer.append(heading+"\n");
				else
					tempbuffer.append(heading+"\t"+field+"\n");
				for(int k=0;k<temp.size();k++)
				{
					String var = (String) temp.get(k).toString();
					tempbuffer.append(var+"\n");					
				}
				buffer = tempbuffer.toString().split("\n");
			} 
			catch (ClassNotFoundException e) 
			{				
			//	e.printStackTrace();
			}
			catch (InstantiationException e) 
			{
				e.printStackTrace();
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
	
	}
	public void queryProcess(){
		getResult();
	}
	

	public Hashtable<Object, Object> getQueryMap() 
	{
		return Querymap;
	}

	public String getQueryName() 
	{
		return QueryName;
	}

	public String[] getQuerybuffer() 
	{
		return Querybuffer;
	}

	public String getReportname() 
	{
		return ReportName;
	}

	public void getResult() 
	{
		Hashtable<Object,Object> table =new Hashtable<Object, Object>();
		table.put("mid", object);
		RecordSearch rs = new RecordSearch();
		rs.setConditionMap(table);
		String line[] = rs.getArrayFromResultSet();
		table.clear();
		for(int i=0;i<line.length;i++)
		{
			String splitline[] = line[i].split("\t");
			String value = splitline[Column.pv_index-1];
			if(value.equals("0"))
				value = splitline[Column.vt_index-1];
			else
				value = gid.getItem(value);
			table.put(gid.getItem(splitline[Column.pid_index-1]), value);
		}
		table = ConvertToLower.convertHashKey(table);
		
		if(table.containsKey("field"))
		{
			 field = table.get("field").toString();
		}	
		
		Ascending ascending = new Ascending();
		ascending.setbuffer(buffer);
		Vector<Object>temp = new Vector<Object>();
		String[] tempbuffer1= Addprefix.removerefix(buffer[0]).split("\t"); 
		//String[] tempbuffer1= buffer[0].split("\t");
		for(int i=0;i<tempbuffer1.length;i++)
		{
			if(tempbuffer1[i].toLowerCase().equals(field.toLowerCase()))
				temp.add(i);
		}
		ascending.setVector(temp,1);
		ascending.getResult();
		buffer = ascending.getbuffer();
		temp.clear();
		int indeoffield=-1;
		String splitbuffer[] = Addprefix.removerefix(buffer[0]).split("\t");
		for(int i=0;i<splitbuffer.length;i++)
		{
			if(splitbuffer[i].toLowerCase().equals(field.toLowerCase()))
				indeoffield = i;
		}
		
		for(int i=1;i<buffer.length;i++)
		{
			try 
			{
				splitbuffer = buffer[i].split("\t");
				String value =splitbuffer[indeoffield];
				String pre_value=value;
				StringBuffer newbuffer = new StringBuffer();
				int j=i;
				while(value.equals(pre_value))
				{	
					pre_value = value;
					newbuffer.append(buffer[j]+"\n");
					try 
					{
						j++;
						splitbuffer = buffer[j].split("\t");
						value =splitbuffer[indeoffield];
					}
					catch (Exception e) 
					{
						value="";
						i++;
						e.printStackTrace();
					}
				}
				i=j-1;
				temp.add(newbuffer.toString().split("\n"));
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		Vector<Object> Result = new Vector<Object>();
		
		String heading = null;
		Enumeration<Object> enumerationtable = table.keys();
		while(enumerationtable.hasMoreElements())
		{
			String key = enumerationtable.nextElement().toString();
			String value = table.get(key).toString();
			Groupbyinterface group;
			try 
			{
				for(int i=0;i<temp.size();i++)
				{
					Class c = Class.forName("combinereport.query.groupby."+CapitalChar.makeFirstCharCapital(key));
					group = (Groupbyinterface) c.newInstance();
					group.setBuffer((String[]) temp.get(i));
					group.initPool();
					group.setobject(gid.getId(table.get(key).toString()));
					group.setField(field);
					group.setheading(buffer[0]);
					group.setreporton(reporton);
					group.getResult();					
					Field = group.getField();
					Result.add(group.getBuffer());
					heading =group.getheading();
				}
				temp.clear();
				for(int k=0;k<Result.size();k++)
				{
					String tempbuffer[] = (String[]) Result.get(k);
					for(int iVar=0;iVar<tempbuffer.length;iVar++)
					{
						temp.add(tempbuffer[iVar]);
					}
				}
				StringBuffer tempbuffer = new StringBuffer();/*
				if(heading.contains(field))
					tempbuffer.append(heading+"\n");
				else
					tempbuffer.append(heading+"\t"+field+"\n");*/
				for(int k=0;k<temp.size();k++)
				{
					String var = (String) temp.get(k).toString();
					tempbuffer.append(var+"\n");					
				}	
				buffer = (heading+"\n"+tempbuffer.toString()).toString().split("\n");
			} 
			catch (ClassNotFoundException e) 
			{				
			//	e.printStackTrace();
			}
			catch (InstantiationException e) 
			{
				e.printStackTrace();
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
	}
	

	public String[] getbuffer() 
	{
		return buffer;
	}

	public String getkey() 
	{
		return Key;
	}

	public String gettablename() 
	{
		return tablename;
	}

	public String gettid() 
	{
		return tid;
	}

	public String getvalue() 
	{
		return Value;
	}

	public void initializeData() 
	{}

	public void setDbmanager() 
	{
		gid = new GetIdName();
		
	}

	public void setKey(String key) 
	{
		this.Key = key;
	}

	public void setObject(String object) 
	{
		this.object = object;
	}

	public void setQueryMap(Hashtable<Object, Object> QueryMap) 
	{	
		this.Querymap = QueryMap;
	}

	public void setQueryName(String QueryName) 
	{
		this.QueryName = QueryName;
	}

	public void setQuerybuffer(String[] Querybuffer) 
	{
		this.Querybuffer  = Querybuffer;
	}

	public void setReportName(String Reportname) 
	{
		this.ReportName = Reportname;
	}

	public void setValue(String value) 
	{
		this.Value = value;
	}

	public void setbuffer(String[] Querybuffer) 
	{
		this.buffer = Querybuffer;
	}

	public void settablename(String tablename) 
	{
		this.tablename = tablename;
	}

	public void settid(String tid) 
	{
		this.tid = tid; 
	}

	public void updateReport() 
	{
		getResult();
	}

	public void setReportmap(Hashtable<Object, Object> ReportMap) 
	{
		this.ReportMap.putAll( ReportMap);
	}

	public void setreporton(String reporton) 
	{	
		this.reporton = reporton;
	}

	public void settypeofreport(String typeofreport) 
	{
		this.typeofreport = typeofreport;
	}

	public void setViewObject(String object, char ch) 
	{
	
		
	}

	
	public void buildQuery() {
		// TODO Auto-generated method stub
		
	}

	
	public String getQuery() {
		// TODO Auto-generated method stub
		return null;
	}

	
	public int getcount() {
		// TODO Auto-generated method stub
		return 0;
	}

	
	public void setConditionMap(Vector<Object> QueryMap) {
		// TODO Auto-generated method stub
		
	}

	
	public void setCount(int count) {
		// TODO Auto-generated method stub
		
	}

	
	public void setMaxcount(int count) {
		// TODO Auto-generated method stub
		
	}

	
	public void setProcess(String process) {
		// TODO Auto-generated method stub
		
	}

	
	public void setQuery(String QueryName) {
		// TODO Auto-generated method stub
		
	}

	
	public void setViewObject(Vector<Object> PropertyMap) {
		// TODO Auto-generated method stub
		
	}

	public void initPool() {
		// TODO Auto-generated method stub
		
	}
}

